package _17_剑指Offer;

public class _67_剑指Offer把字符串转换成整数 {

    public static void main(String[] args) {
        _67_剑指Offer把字符串转换成整数 v = new _67_剑指Offer把字符串转换成整数();

        System.out.println(v.strToInt("  0000000000012345678"));
    }

    public int strToInt(String str) {
        str = str.trim();
        char[] chars = str.toCharArray();
        if (str.length() == 0) return 0;
        // 判断第一个符号
        boolean isSymbol = true;
        boolean isFirstNum = false;
        char first = chars[0];
        if (first == '-') {
            isSymbol = false;
        } else if (str.charAt(0) == '+') {

        } else if (Character.isDigit(first)) {
            isFirstNum = true;
        } else {
            return 0;
        }
        long value = 0;
        for (int i = isFirstNum? 0: 1; i < chars.length; i++) {
            char cur = chars[i];
            if (cur >= '0' && cur <= '9') {
                value =  10 * value + (cur - '0');
                // 判断是否越界
                if (isSymbol && value > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
                if (!isSymbol && -value < Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                }
            } else {
                break;
            }
        }
        return (int) (isSymbol? value: -value);
    }

}
